/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.base;

import org.webos.java.base.Session;
import java.util.ArrayList;
import java.util.List;
import org.webos.java.base.users.UserProfile;
import org.webos.java.root.Log;
import org.webos.java.root.RandomGUID;

/**
 *
 * @author Kostya
 */
public class SessionManager {

    private static List<Session> sessions = new ArrayList<Session>();
//    private static Session _default = null;

    public static Session getSessionByID(String aID){
        for (int i = 0; i < sessions.size(); i++) {
            Session session = sessions.get(i);
            if(session.getId().equals(aID))
                return session;
        }
        return null;
    }

    public static Session getSession(String aKey){
        for (int i = 0; i < sessions.size(); i++) {
            Session session = sessions.get(i);
            if(session.getSessionKey().equals(aKey))
                return session;
        }
        return null;
    }

    static {
//        _default = new Session();
//        sessions.add(_default);
    }

    public static Session createSession(String aLogin, String aPassword){
        if(aLogin==null || aLogin.equals("") || aPassword==null || aPassword.equals(""))
            return null;
        Log.debug(null, "User provider: "+UserManager.getProvider());
        UserProfile profile = UserManager.getProvider().checkUser(aLogin, aPassword);
        if(profile==null)
            return null;
        Log.info(null, "For user", aLogin, "userCode is "+profile.getId());
        for (int i = 0; i < sessions.size(); i++) {
            Session session = sessions.get(i);
            if(session==null)
                continue;
//            Log.debug(null, "check session:", aLogin, aPassword,
//                    session.getLogin(), session.getPassword());
            if(session.getLogin().equalsIgnoreCase(aLogin)){
                session.setSessionKey(new RandomGUID().toString());
                session.updateSession(profile);
                return session;
            }
        }
        Session sess = new Session(new RandomGUID().toString(), aLogin, aPassword, profile);
        sessions.add(sess);
        Log.info(null, "New session created for user "+aLogin+", sessions: "+sessions.size());
        return sess;
    }

    public static int getSessionCount(){
        return sessions.size();
    }

    public static Session getSessionAt(int i){
        return sessions.get(i);
    }
    
}
